package com.zrrd.yunchmall.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.yunchmall.user.entity.Admin;
import com.zrrd.yunchmall.user.entity.Role;
import com.zrrd.yunchmall.user.service.IAdminService;
import com.zrrd.yunchmall.user.util.JwtUtil;
import com.zrrd.yunchmall.util.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author LYY
 * @since 2024-01-15
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/admin")
@Api(tags = "权限符-管理员模块")
public class AdminController {
    @Autowired
    private IAdminService adminService;


    /*
  1. 请求路径?a=1&b=2 @RequestParam
  2. 请求路径/1/2 @PathVariable
  3. POST请求，并且参数使用JSON格式封装 {"a":1, "b":2} @RequestBody
   */
    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public ResponseResult login(@ApiParam(required = true) @RequestBody Admin admin){
        String token=adminService.login(admin.getUsername(),admin.getPassword());
        if (token!=null){
            return new ResponseResult<>(200,"登录成功！",token);
        }
        else {
            return new ResponseResult<>(401,"用户名或密码错误！",null);
        }
    }

    @ApiOperation("获取管理员信息")
    @GetMapping("/info")
    public ResponseResult<Admin>info(@RequestHeader("Authorization") String token){
        //返回一个封装了id和用户名的admin对象
        Admin admin= JwtUtil.parseAdminToken(token.substring(7));
        admin=adminService.setPermissionInfo(admin);
        return new ResponseResult<>(200,"查询成功",admin);
    }


    @ApiOperation("优雅退出")
    @PostMapping("/logout")
    public ResponseResult logout(){
        //从redis中将token设计过期
        return new ResponseResult<>(200,"优雅退出",null);
    }

    @ApiOperation("查询管理员列表")
    @GetMapping("/list")
    public ResponseResult list(@ApiParam(required = true,defaultValue = "10") @RequestParam int pageSize,
                               @ApiParam(required = true,defaultValue = "1") @RequestParam int pageNum,
                               @ApiParam  String keyword){
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        //当关键字不为空
        if (!StringUtils.isEmpty(keyword)){
            //需要与数据库字段名对应
            queryWrapper.eq("username",keyword).or().eq("nike_name",keyword);
        }
        IPage<Admin>pageInfo= adminService.page(new Page<>(pageNum,pageSize),queryWrapper);
        return new ResponseResult<>(200,"查询成功",pageInfo);
    }

    @PostMapping("/register")
    @ApiOperation("添加一个管理员")
    public ResponseResult register(@RequestBody Admin admin){
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",admin.getUsername());
        if(adminService.count(queryWrapper)>0){
            return new ResponseResult(205,"注册失败:用户名已存在");
        }
        String passText=admin.getPassword();
        String secretPass= BCrypt.hashpw(passText,BCrypt.gensalt());
        admin.setCreateTime(LocalDateTime.now());
        admin.setPassword(passText);
        adminService.save(admin);
        return new ResponseResult<>(200,"注册成功",admin);
    }
    @ApiOperation("修改管理员信息")
    @PostMapping("/update/{id}")
    public ResponseResult update(@RequestBody Admin admin,@PathVariable("id") long id){
        UpdateWrapper updateWrapper=new UpdateWrapper();
        //where语句
        updateWrapper.eq("id",id);
        adminService.update(admin,updateWrapper);
        return new ResponseResult(200,"修改成功");
    }
    @ApiOperation("删除管理员账号")
    @PostMapping("/delete/{id}")
    public ResponseResult delete(@PathVariable("id") long id){
        adminService.removeById(id);
        return new ResponseResult(200,"删除成功");
    }

    @ApiOperation("修改管理员状态")
    @PostMapping("/updateStatus/{id}")
    public ResponseResult update(@RequestParam int status,@PathVariable("id") long id){
        UpdateWrapper updateWrapper=new UpdateWrapper();
        //where语句
        updateWrapper.eq("id",id);
        updateWrapper.set("status",status);
        adminService.update(updateWrapper);
        return new ResponseResult(200,"修改成功！");
    }

    @ApiOperation("查询管理员角色")
    @GetMapping ("/role/{id}")
    public ResponseResult selectAdminRole(@PathVariable("id") long id){
        List<Role>roles=adminService.getRoleList(id);

        return new ResponseResult(200,"查询成功！",roles);
    }

    @ApiOperation("分配管理员角色")
    @PostMapping("/role/{id}")
    public ResponseResult allocRole(@RequestParam long adminId,@RequestParam String roleIds){
        adminService.allocRole(adminId,roleIds);
        return new ResponseResult(200,"查询成功！");
    }
    @GetMapping("/testSleuth")
    public String testSleuth(){
        return "管理员:测试链路追踪";
    }



}
